<?php

namespace app\admin\controller;

use think\Db;
use app\common\service\GuguService;
use app\common\model\Major;
use app\common\model\School;

class DataSync extends Base
{
    public function school_line()
    {
		if ($this->request->isPost()) {
			
            $type = input('type');
            $page = input('page','1');
			if ($type == 'schoolline') {
				$this->error('不能操作');
				
				/*测试使用_start*/ //PROVINCENAME 或 COLLEGENAME
				//$result = GuguService::make('/metadata/ceecollegeline',['appkey'=>'UZ8X3YJWLFJWJKY28U63K8YFUTQZX4RD','pageIndex'=>60,'pageSize'=>20,'searchType'=>'PROVINCENAME','keyword'=>'河南']);
				//dump($result);die;
				/*测试使用_end*/
				Db::startTrans();
				if($page == 1){
					Db::execute('TRUNCATE TABLE `think_school_line`');
				}
				$result = GuguService::make('/metadata/ceecollegeline',['appkey'=>'UZ8X3YJWLFJWJKY28U63K8YFUTQZX4RD','pageindex'=>$page,'pagesize'=>100,'searchtype'=>'COLLEGENAME','keyword'=>'清华大学']);
				if($result[0] != 200){
				   $this->error($result[1]??'error');
				}
				$page_total = ceil($result[1][0]['DataTotalCount']/100);
				$is_end = ($page_total == $page)?1:0;
				//$is_end = (5 == $page)?1:0;//dump($result);die;
				
				$dataM = [];
				$nowtime = time();
				if(!empty($result[1][1])){
					foreach($result[1][1] as $k=>$v){
						$dataM[] = ['province'=>$v['Province'],'school_uuid'=>$v['SchoolUUID'],'college_name'=>$v['CollegeName'],'year'=>$v['Year'],'highest_score'=>$v['HighestScore'],'average_score'=>$v['AverageScore'],'lowest_score'=>$v['LowestScore'],'lowest_rank'=>$v['LowestRank'],'provincial_controlLine'=>$v['ProvincialControlLine'],'enrollment_type'=>$v['EnrollmentType'],'selection_level'=>$v['SelectionLevel'],'admission_batch'=>$v['AdmissionBatch'],'type_name'=>$v['TypeName'],'course_selection'=>$v['CourseSelection'],
						'course_selection_name'=>$v['CourseSelectionName'],
						'school_type'=>$v['SchoolType'],'school_in_city'=>$v['SchoolInCity'],
						'is985'=>$v['Is985'],
						'is211'=>$v['Is211'],'is_dual_class'=>$v['IsDualClass'],'cover_image'=>$v['CoverImage'],
						'create_time'=>$nowtime,'update_time'=>$nowtime];
					}
				}
				if(!empty($dataM)){
					$flag = Db::name('school_line')->insertAll($dataM);
					if(!$flag){
						Db::rollback();
						$this->error('出错');
					}
				}
				Db::commit();
				$this->success('成功','',['page_total'=>$page_total,'page'=>$page,'is_end'=>$is_end]);
            }elseif($type == 'major') {
				$this->error('不能操作');
				
				/*测试使用_start*/ //PROVINCENAME 或 COLLEGENAME
				$result = GuguService::make('/metadata/ceemajorline',['appkey'=>'TZK6DJZ5LVS6V8LYDAS9WE3K4TM8ZQWZ','pageIndex'=>1,'pageSize'=>100,'schoolname'=>'清华大学']);
				//dump($result);die;
				/*测试使用_end*/
				Db::startTrans();
				if($page == 1){
					Db::execute('TRUNCATE TABLE `think_major_line`');
				}
				$result = GuguService::make('/metadata/ceemajorline',['appkey'=>'TZK6DJZ5LVS6V8LYDAS9WE3K4TM8ZQWZ','pageindex'=>$page,'pagesize'=>100,'schoolname'=>'清华大学']);
				if($result[0] != 200){
				   $this->error($result[1]??'error');
				}
				$page_total = ceil($result[1][0]['DataTotalCount']/100);
				$is_end = ($page_total == $page)?1:0;
				$is_end = (5 == $page)?1:0;//dump($result[1][1]);die;
				
				$dataM = [];
				$nowtime = time();
				if(!empty($result[1][1])){
					foreach($result[1][1] as $k=>$v){
						$dataM[] = ['province_name'=>$v['ProvinceName'],'school_uuid'=>$v['SchoolUUID'],'school_name'=>$v['SchoolName'],'major_name'=>$v['MajorName'],'major_code'=>$v['MajorCode'],'year'=>$v['Year'],'high_socre'=>$v['HighSocre'],'average_score'=>$v['AverageScore'],'lowest_score'=>$v['LowestScore'],'lowest_section'=>$v['LowestSection'],'batch_name'=>$v['BatchName'],'type_name'=>$v['TypeName'],'pro_score'=>$v['ProScore'],'subject_selection'=>$v['SubjectSelection'],
						'major_standard_code'=>$v['MajorStandardCode'],
						'create_time'=>$nowtime];
					}
				}
				if(!empty($dataM)){
					$flag = Db::name('major_line')->insertAll($dataM);
					if(!$flag){
						Db::rollback();
						$this->error('出错');
					}
				}
				Db::commit();
				$this->success('成功','',['page_total'=>$page_total,'page'=>$page,'is_end'=>$is_end]);
            }else {
                $this->error('非法访问');
            }
		}else{
			
			return $this->fetch();
		}
	}
	
	//同步咕咕接口专业和院校数据
	public function data_update()
    {
		if (!$this->request->isPost()) {
            return $this->fetch();
        } else {
			/*测试使用_start*/
			//$result = GuguService::make('/metadata/ceemajor',['appkey'=>'UYH83DDP7NARHVCFP8J5KMXWMQQUJKHJ','pageindex'=>91,'pagesize'=>20]);
			//dump($result);
			/*测试使用_end*/
			
            $type = input('type');
            $page = input('page','1');
            if ($type == 'major') {
				Db::startTrans();
				if($page == 1){
					//Db::name('major')->truncate(false);
					Db::execute('TRUNCATE TABLE `think_major`');
				}
				$result = GuguService::make('/metadata/ceemajor',['appkey'=>'UYH83DDP7NARHVCFP8J5KMXWMQQUJKHJ','pageindex'=>$page,'pagesize'=>20]);
				if($result[0] != 200){
				   $this->error($result[1]??'error');
				}
				$page_total = ceil($result[1][0]['DataTotalCount']/20);
				$is_end = ($page_total == $page)?1:0;
				//$is_end = (5 == $page)?1:0;
				//dump($result[1][1]);die;
				$dataM = [];
				$nowtime = time();
				if(!empty($result[1][1])){
					foreach($result[1][1] as $k=>$v){
						$dataM[] = ['cate_title'=>$v['MajorName'],'education_level'=>$v['EducationLevel'],'disciplinary_category'=>$v['DisciplinaryCategory'],'disciplinary_sub_category'=>$v['DisciplinarySubCategory'],'major_code'=>$v['MajorCode'],'major_name'=>$v['MajorName'],'major_introduction'=>$v['MajorIntroduction'],'courses'=>json_encode($v['Courses'],JSON_UNESCAPED_UNICODE),'graduate_scale'=>$v['GraduateScale'],'male_female_ratio'=>$v['MaleFemaleRatio'],'recommend_schools'=>json_encode($v['RecommendSchools'],JSON_UNESCAPED_UNICODE),'create_time'=>$nowtime,'update_time'=>$nowtime];
					}
				}
				if(!empty($dataM)){
					$flag = Db::name('major')->insertAll($dataM);
					if(!$flag){
						Db::rollback();
						$this->error('出错');
					}
				}
				Db::commit();
				$this->success('成功','',['page_total'=>$page_total,'page'=>$page,'is_end'=>$is_end]);
            }elseif ($type == 'school') {
				Db::startTrans();
				if($page == 1){
					Db::execute('TRUNCATE TABLE `think_school`');
				}
				$result = GuguService::make('/location/college',['appkey'=>'GBMRZEXWA8X8XYE9HYREHBWY3M4LPMMS','keywords'=>'','pageindex'=>$page,'pagesize'=>20]);
				if($result[0] != 200){
				   $this->error($result[1]??'error');
				}
				$page_total = ceil($result[1][0]['DataTotalCount']/20);
				$is_end = ($page_total == $page)?1:0;
				//$is_end = (5 == $page)?1:0;
				//dump($result[1][1]);die;
				$dataI = [];
				$dataU = [];
				$nowtime = time();
				if(!empty($result[1][1])){
					foreach($result[1][1] as $k=>$v){
						$data_id = $v['DataId'];
						$flag = Db::name('school')->where('data_id',$data_id)->value('id');
						if(!empty($flag)){
							$dataU[$k] = ['id'=>$flag,'school_uuid'=>$v['SchoolUUID'],'college_name'=>$v['CollegeName'],'province'=>$v['Province'],'city'=>$v['City'],'district'=>$v['District'],'coordinate'=>$v['Coordinate'],
							
							'college_type'=>$v['CollegeType'],'is985'=>($v['Is985'])?1:0,'is211'=>($v['Is211'])?1:0,'is_dual_class'=>($v['IsDualClass'])?1:0,
							'college_category'=>$v['CollegeCategory'],'college_tags'=>$v['CollegeTags'],'edu_level'=>$v['EduLevel'],'college_property'=>$v['CollegeProperty'],
							'college_code'=>$v['CollegeCode'],'ranking'=>$v['Ranking'],'rankingIn_category'=>$v['RankingInCategory'],'web_site'=>$v['WebSite'],
							'call_number'=>$v['CallNumber'],'email'=>$v['Email'],'address'=>$v['Address'],'cover_image'=>$v['CoverImage'],
							'intro'=>$v['Intro'],'expenses'=>$v['Expenses'],'old_name'=>$v['OldName'],'short_name'=>$v['ShortName'],
							'major_list'=>json_encode($v['MajorList'],JSON_UNESCAPED_UNICODE),'update_time'=>$nowtime];
						}else{
							$dataI[$k] = ['data_id'=>$v['DataId'],'school_uuid'=>$v['SchoolUUID'],'college_name'=>$v['CollegeName'],'province'=>$v['Province'],'city'=>$v['City'],'district'=>$v['District'],'coordinate'=>$v['Coordinate'],
							
							'college_type'=>$v['CollegeType'],'is985'=>($v['Is985'])?1:0,'is211'=>($v['Is211'])?1:0,'is_dual_class'=>($v['IsDualClass'])?1:0,
							'college_category'=>$v['CollegeCategory'],'college_tags'=>$v['CollegeTags'],'edu_level'=>$v['EduLevel'],'college_property'=>$v['CollegeProperty'],
							'college_code'=>$v['CollegeCode'],'ranking'=>$v['Ranking'],'rankingIn_category'=>$v['RankingInCategory'],'web_site'=>$v['WebSite'],
							'call_number'=>$v['CallNumber'],'email'=>$v['Email'],'address'=>$v['Address'],'cover_image'=>$v['CoverImage'],
							'intro'=>$v['Intro'],'expenses'=>$v['Expenses'],'old_name'=>$v['OldName'],'short_name'=>$v['ShortName'],
							'major_list'=>json_encode($v['MajorList'],JSON_UNESCAPED_UNICODE),'create_time'=>$nowtime,'update_time'=>$nowtime];
						}
						
					}
				}
				if(!empty($dataI)){
					$flag = Db::name('school')->insertAll($dataI);
					if(!$flag){
						Db::rollback();
						$this->error('出错1');
					}
				}
				if(!empty($dataU)){
					$obj = new School();
					$flag = $obj->saveAll($dataU);
					if($flag == false){
						Db::rollback();
						$this->error('出错2');
					}
				}
				Db::commit();
				$this->success('成功','',['page_total'=>$page_total,'page'=>$page,'is_end'=>$is_end]);
            } else {
                $this->error('非法访问');
            }
        }
    }
	//同步专业数据后，更新专业数据结构
	public function major_column()
    {
		if ($this->request->isPost()) {
            $disciplinary_categorys = Db::name('major')->group('education_level,disciplinary_category')->where('cate_level',3)->order('id asc')->select();
			//dump($disciplinary_categorys);die;
			Db::name('major')->where('cate_level','<>',3)->delete();
			$count = Db::name('major')->count();
			$count = $count+1;
			Db::execute("ALTER TABLE think_major AUTO_INCREMENT = $count;");
			
			$nowtime = time();
			if(!empty($disciplinary_categorys)){
				Db::startTrans();
				$dataM1 = [];
				foreach($disciplinary_categorys as $k=>$v){
					$dataM1[$k] = ['cate_level'=>1,'cate_title'=>$v['disciplinary_category'],'education_level'=>$v['education_level'],'disciplinary_category'=>$v['disciplinary_category'],'major_code'=>substr($v['major_code'],0,2),'create_time'=>$nowtime,'update_time'=>$nowtime];
				}
				if(!empty($dataM1)){
					$flag = Db::name('major')->insertAll($dataM1);
					if(!$flag){
						$this->error('出错');
					}
				}
				
				$disciplinary_categorys = Db::name('major')->where('cate_level',1)->order('id asc')->select();
				//dump($disciplinary_categorys);
				foreach($disciplinary_categorys as $k1=>$v1){
					$disciplinary_sub_categorys = Db::name('major')->where('education_level',$v1['education_level'])->where('disciplinary_category',$v1['disciplinary_category'])->where('cate_level',3)->group('disciplinary_sub_category')->order('id asc')->select();
					$dataM2 = [];
					foreach($disciplinary_sub_categorys as $k2=>$v2){
						$dataM2[$k2] = ['cate_level'=>2,'cate_title'=>$v2['disciplinary_sub_category'],'cate_pid'=>$v1['id'],'education_level'=>$v2['education_level'],'disciplinary_category'=>$v2['disciplinary_category'],'disciplinary_sub_category'=>$v2['disciplinary_sub_category'],'major_code'=>substr($v2['major_code'],0,4),'create_time'=>$nowtime,'update_time'=>$nowtime];
					}
					if(!empty($dataM2)){
						$flag = Db::name('major')->insertAll($dataM2);
						if(!$flag){
							$this->error('出错');
						}
					}
				}
				//dump($dataM2);die;
				/*$major_names = Db::name('major')->field('id,education_level,disciplinary_category,disciplinary_sub_category')->where('cate_level',3)->select();
				$dataU = [];
				foreach($major_names as $k3=>$v3){
					$cate_pid = Db::name('major')->where('education_level',$v3['education_level'])->where('disciplinary_category',$v3['disciplinary_category'])->where('disciplinary_sub_category',$v3['disciplinary_sub_category'])->where('cate_level',2)->value('id');
					$dataU[$k3] = ['id'=>$v3['id'],'cate_pid'=>$cate_pid];
				}
				if(isset($dataU) && !empty($dataU)) {
					$obj = new Major();
					$obj->saveAll($dataU);
				}*/
				$nums = 1;
				Db::name('major')->field('id,education_level,disciplinary_category,disciplinary_sub_category')->where('cate_level',3)->chunk(100, function ($list) use(&$nums){
					$dataU = [];	
					foreach($list as $k3=>$v3){
						$cate_pid = Db::name('major')->where('education_level',$v3['education_level'])->where('disciplinary_category',$v3['disciplinary_category'])->where('disciplinary_sub_category',$v3['disciplinary_sub_category'])->where('cate_level',2)->value('id');
						$dataU[$k3] = ['id'=>$v3['id'],'cate_pid'=>$cate_pid];
					}
					if(isset($dataU) && !empty($dataU)) {
						$obj = new Major();
						$obj->saveAll($dataU);
					}
					$nums++;
				
				});
				
				Db::commit();
				$this->success('成功'.$nums);
			}else{
				Db::rollback();
				$this->error('失败');
			}
        }else{
			$this->error('非法访问');
		}
	}
	//同步院校数据后，更新院校数据适配系统
	public function school_column()
    {	
		set_time_limit(0); 
		Db::startTrans();
		$nums = 1;
		Db::name('school')->field('id,province,city,district,college_category,college_property,edu_level,college_tags,is985,is211,is_dual_class')->chunk(100, function ($list) use(&$nums){
			$dataU = [];	
			foreach($list as $k=>$v){
				//$college_tags = preg_replace("/[\[\]]/","",$v['college_tags']);
				//$college_tag_arr = explode(',',$college_tags);
				//dump($college_tag_arr);die;
				$type_id = Db::name('school_type')->where('title_fu',$v['college_category'])->value('id');//综合、体育。。。
				if($v['college_property'] == '公办'){
					$school_xingzhi = 1;
				}elseif($v['college_property'] == '民办'){
					$school_xingzhi = 2;
				}else{
					$school_xingzhi = 3;
				}
				if($v['edu_level'] == '普通本科' || $v['edu_level'] == '本科'){
					$school_xingzhi2 = 1;
				}else{
					$school_xingzhi2 = 2;
				}
				
				$school_tese = [];
				if($v['is985'] == 1){
					$school_tese[] = 1;
				}
				if($v['is211'] == 1){
					$school_tese[] = 2;
				}
				if($v['is_dual_class'] == 1){
					$school_tese[] = 3;
				}
				if(!empty($school_tese)){
					Db::name('school_tese_data')->where('school_id',$v['id'])->delete();
					$school_tese = array_filter($school_tese);
					$dataTs = [];
					foreach ($school_tese as $val) {
						 $dataTs[] = ['tese_id' => $val, 'school_id' => $v['id']];
					}
					Db::name('school_tese_data')->insertAll($dataTs);
				}
				$province_id = Db::name('area')->where('level',1)->where('name',$v['province'])->value('id');
				$city_id = Db::name('area')->where('level',2)->where('name',$v['province'])->value('id');
				$xian_id = Db::name('area')->where('level',3)->where('name',$v['province'])->value('id');
					
				$dataU[$k] = ['id'=>$v['id'],'province_id'=>$province_id,'city_id'=>$city_id,'xian_id'=>$xian_id,'school_type'=>$type_id,'school_xingzhi'=>$school_xingzhi,'school_xingzhi2'=>$school_xingzhi2];
			}
			if(isset($dataU) && !empty($dataU)) {
				$obj = new School();
				$obj->saveAll($dataU);
			}
			$nums++;
		
		})->order('id asc');
		Db::commit();
		$this->success('成功'.$nums);
	}
	
}